$(document).ready(function () {
    // 初始化批量删除事件
    initBulkDelete();
});

// 批量删除功能模块
function initBulkDelete() {
    // 事件委托处理复选框点击
    $('.main-container').on('click', '.case-checkbox', function () {
        toggleDeleteButtonState();
    });

    // 删除按钮点击事件
    $('#delete-selected').click(async function () {
        const selectedIds = getSelectedCaseIds();

        if (!selectedIds.length) {
            showAlert('请使用复选框选择至少一个用例', 'warning');
            return;
        }

        const confirmed = await showDeleteConfirmation(selectedIds.length);
        if (!confirmed) return;

        executeBulkDelete(selectedIds);
    });
}

// 获取选中用例ID
function getSelectedCaseIds() {
    return $('.case-checkbox:checked').map(function () {
        return parseInt($(this).val());
    }).get();
}

// 执行删除请求
function executeBulkDelete(ids) {
    const payload = {
        case_ids: ids,
        operation: "delete",
    };

    showLoadingState(true);

    $.ajax({
        url: '/api/cases/delete-cases/',  // 在模板中定义的URL
        method: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(payload),
    })
        .done(function (response) {
            if (response.status === 'success') {
                // 根据返回的详细ID进行删除
                handleDeleteSuccess(response.deleted_count, ids);
            } else {
                showAlert(`操作失败：${response.message}`, 'danger');
            }
        })
        .fail(handleAjaxError)
        .always(() => showLoadingState(false));
}

// 删除成功处理
function handleDeleteSuccess(deletedCount, ids) {
    // 移除已删除的卡片
    ids.forEach(id => {
        $(`input[value="${id}"]`).closest('.test-case-card').fadeOut(300, function () {
            $(this).remove();
        });
    });

    // 更新页面计数等
    updateUIAfterDeletion(deletedCount);

    showAlert(`成功删除 ${deletedCount} 个用例`, 'success');
}

// 工具函数 ========================================

// 获取CSRF令牌
// function getCSRFToken() {
//     return document.querySelector('[name=csrfmiddlewaretoken]').value;
// }

// 显示加载状态
function showLoadingState(loading) {
    const $btn = $('#delete-selected');
    $btn.prop('disabled', loading);
    $btn.html(loading ?
        '<i class="fas fa-spinner fa-spin"></i> 处理中...' :
        '<i class="bi bi-trash me-2"></i>删除选中'
    );
}

// 确认对话框
function showDeleteConfirmation(count) {
    return new Promise((resolve) => {
        const modalHtml = `
        <div class="modal fade" id="confirmModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">确认删除</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <p>确定要删除选中的 <strong>${count}</strong> 个用例吗？</p>
                        <p class="text-danger small">此操作不可撤销！</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-danger" id="confirmDelete">确认删除</button>
                    </div>
                </div>
            </div>
        </div>`;

        const $modal = $(modalHtml).appendTo('body');
        $modal.modal('show');

        $modal.on('click', '#confirmDelete', function () {
            $modal.modal('hide');
            resolve(true);
        });

        $modal.on('hidden.bs.modal', function () {
            $modal.remove();
            resolve(false);
        });
    });
}

// 更新UI状态
function updateUIAfterDeletion(count) {
    // 示例：更新分页计数
    const $countBadge = $('.total-count');
    if ($countBadge.length) {
        const newCount = parseInt($countBadge.text()) - count;
        $countBadge.text(newCount);
    }
}

// 错误处理
function handleAjaxError(xhr) {
    let errorMsg = '请求失败：';
    try {
        // 尝试解析不同格式的错误响应
        const response = xhr.responseJSON || JSON.parse(xhr.responseText);
        errorMsg += response.message || xhr.statusText;
    } catch (e) {
        errorMsg += `[${xhr.status}] ${xhr.statusText}`;
    }
    showAlert(errorMsg, 'danger');
    showAlert(errorMsg, 'danger');
}

// 显示浮动提示
function showAlert(message, type = 'info') {
    const alertHtml = `
    <div class="alert alert-${type} alert-dismissible fade show floating-alert">
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>`;

    $(alertHtml)
        .appendTo('body')
        .delay(3000)
        .fadeOut(400, function () {
            $(this).alert('close');
        });
}

// 切换删除按钮状态
function toggleDeleteButtonState() {
    const hasSelections = $('.case-checkbox:checked').length > 0;
    $('#delete-selected').prop('disabled', !hasSelections);
}